package com.example.socket.server;

import com.example.pojo.CollarMsg;
import com.example.pojo.MapMsg;
import com.example.service.collar.CollarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author w
 */
@Component
@ServerEndpoint("/websocket/{ip}")
public class WebSocketServer {

    private static CollarService collarService;

    @Autowired
    public void init(CollarService collarService) {
        WebSocketServer.collarService = collarService;
    }

    /**
     * 所有在线会话
     */
    public static Map<String, Session> onlineSessions = new ConcurrentHashMap<String, Session>();

    /**
     * 连接成功
     */
    @OnOpen
    public void onOpen(@PathParam(value = "ip") String ip, Session session) throws IOException {
        onlineSessions.putIfAbsent(ip, session);
        System.out.println("在线情况："+onlineSessions);
    }
 
    /**
     * 客户端发送消息调用
     */
    @OnMessage
    public void onMessage(@PathParam(value = "ip") String ip, String msg) throws Exception {
        if ("recent".equals(msg)){
            CollarMsg recentlyCollarMsg = collarService.getRecentlyCollarMsg(ip);
            net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(recentlyCollarMsg);
            onlineSessions.get(ip).getBasicRemote().sendText(json.toString());
        }else if ("map".equals(msg)){
            List<MapMsg> publicPetMap = collarService.getPublicPetMap(ip);
            net.sf.json.JSONArray json = net.sf.json.JSONArray.fromObject(publicPetMap);
            onlineSessions.get(ip).getBasicRemote().sendText(json.toString());
        }
    }
 
    /**
     * 连接关闭
     */
    @OnClose
    public void onClose(@PathParam(value = "ip") String ip, Session session) {
        if (onlineSessions.get(ip)!=null){
            onlineSessions.remove(ip);
            System.out.println("项圈 "+ip+" 下线！当前在线数量为："+onlineSessions.size());
        }
    }
 
    /**
     * 连接错误
     */
    @OnError
    public void onError(@PathParam(value = "ip") String ip, Throwable error) throws IOException {
        error.printStackTrace();
        System.out.println(ip+"连接出错！");
//        if (!"admin".equals(id)){
//            adminSendNotice(id,"连接出错！："+error.getMessage());
//        }
    }
}